import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import ViteCompression from 'vite-plugin-compression'
import type { ConfigEnv, UserConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const { VITE_REPORT, VITE_BUILD_GZIP, VITE_DROP_CONSOLE, VITE_PORT } = loadEnv(
    mode,
    process.cwd()
  )
  return {
    resolve: {
      alias: [
        {
          find: '@',
          replacement: resolve(__dirname, 'src')
        },
        {
          find: 'views',
          replacement: resolve(__dirname, 'src/views')
        }
      ]
    },
    server: {
      host: '0.0.0.0',
      port: Number(VITE_PORT),
      cors: true,
      proxy: {
        '/service1': {
          // target: 'http://itmsdev.wingtech.com/service1',
          target: 'http://192.168.47.52:30101/service1',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/service1/, '')
        }
      }
    },
    plugins: [
      react(),
      // 是否生成包预览
      VITE_REPORT === 'true' && visualizer(),
      // 是否使用gzip压缩
      VITE_BUILD_GZIP === 'true' &&
        ViteCompression({
          verbose: true,
          disable: false,
          threshold: 10240,
          algorithm: 'gzip',
          ext: '.gz'
        })
    ],
    esbuild: {
      // 线上的会把console和debugger去除
      pure: VITE_DROP_CONSOLE === 'true' ? ['console.log', 'debugger'] : []
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets', // 指定静态资源存放路径
      // esbuild 打包更快，但是不能去除console，需要去掉console要在esbuild中配置，terser模式可以去掉console
      // 注意：使用terser模式，在vite3以上需要下载，pnpm i terser -D
      minify: 'esbuild', // esbuild | terser
      // terserOptions: {
      //   compress: {
      //     drop_console: Boolean(VITE_DROP_CONSOLE)
      //   }
      // },
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]'
        }
      }
    }
  }
})
